<?php

declare(strict_types=1);

namespace Service\MnCheckUserService;

use App\Model\BbcModel\MnCheckUser;
use App\Model\BbcModel\Salesperson;
use Service\BaseService;
use Service\Code\Normal;
use Service\CacheService\CacheProviderService as Cache;

class MnCheckUserService extends BaseService
{
    /**
     * 提交资料审核
     * @param integer $mnid
     * @param string $mobile
     * @param string $name
     * @param integer $cid
     * @param string $invite_code
     * @param integer $mid
     * @return array
     */
    public function applyUser(int $mnid, string $mobile, string $name, int $cid, string $invite_code, int $mid): array
    {
        if (empty($mid)) {
            return Normal::returnCode(Normal::FAIL, '请先登录');
        }
        $cache_key = "AuthInfo_CheckAuthInfo_{$mid}";
        $check_times = Cache::getCacheByKey($cache_key) ?? 0;
        if (!empty($check_times) && $check_times >= 3) {
            return Normal::returnCode(Normal::FAIL, '操作太频繁');
        }
        $isExistMnUser = MnCheckUser::instance()->info([
            'mid'  => $mid,
            'mnid' => $mnid,
            'cid'  => $cid,
            '_order_' => 'id desc'
        ]);
        if (!empty($isExistMnUser)) {
            if ($isExistMnUser['status'] == 0) {
                return Normal::returnCode(Normal::FAIL, '您已提交审核，还在审核中');
            }
            if ($isExistMnUser['status'] == 1) {
                return Normal::returnCode(Normal::FAIL, '您已通过审核');
            }
        }
        $insertMnUser = [
            'mnid' => $mnid,
            'mobile' => $mobile,
            'name' => $name,
            'cid' => $cid,
            'mid' => $mid,
            'cd' => time(),
            'check_time' => time(),
            'status' => 1,
            'check_user' => '自动通过'
        ];
        if (!empty($invite_code)) {
            $saler = Salesperson::instance()->info(['invite_code' => $invite_code]);
            if (empty($saler)) {
                return Normal::returnCode(Normal::FAIL, '销售人员不存在');
            }
            if ($saler['status'] != 1) {
                return Normal::returnCode(Normal::FAIL, '销售人员已被禁用');
            }
            $insertMnUser['sale_id'] = $saler['id'];
        }
        $mnUserId = MnCheckUser::instance()->add($insertMnUser);
        if(!$mnUserId){
            return Normal::returnCode(Normal::FAIL, '申请失败');
        }
        return Normal::returnCode(Normal::SUC, '申请成功');
    }
}
